package com.breeze.components.task.xxl.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.breeze.components.core.exception.CommonException;
import com.breeze.components.task.xxl.config.properties.XxlJobProperties;
import com.breeze.components.task.xxl.service.JobLoginService;
import jakarta.annotation.Resource;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.stereotype.Service;

/**
 * @author breeze
 */
@Service
public class JobLoginServiceImpl implements JobLoginService {

  /** cookie标识 */
  private static final String COOKIE_KEY = "XXL_JOB_LOGIN_IDENTITY";

  private final Map<String, String> loginCookie = new HashMap<>(8);
  @Resource XxlJobProperties properties;

  @Override
  public void login() {
    try {
      String url = properties.getAdminAddresses() + "/login";
      HttpResponse response =
          HttpRequest.post(url)
              .form("userName", properties.getUsername())
              .form("password", properties.getPassword())
              .execute();
      List<HttpCookie> cookies = response.getCookies();
      HttpCookie httpCookie =
          cookies.stream()
              .filter(cookie -> cookie.getName().equals(COOKIE_KEY))
              .findFirst()
              .orElseThrow(() -> new CommonException("get xxl-job cookie error!"));
      String value = httpCookie.getValue();
      loginCookie.put(COOKIE_KEY, value);
    } catch (Exception ex) {
      throw new CommonException("get xxl-job cookie error!");
    }
  }

  @Override
  public String getCookie() {
    for (int i = 0; i < 3; i++) {
      String cookieStr = loginCookie.get(COOKIE_KEY);
      if (Objects.nonNull(cookieStr)) {
        return COOKIE_KEY + "=" + cookieStr;
      }
      login();
    }
    throw new RuntimeException("get xxl-job cookie error!");
  }
}
